package com.rc.saas.tenant.controller.ugs;

import com.alibaba.fastjson.JSONArray;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.component.UidGenerator;
import com.rc.saas.tenant.common.constant.ShiroConstants;
import com.rc.saas.tenant.common.sms.AliyunSmsTemplateEnum;
import com.rc.saas.tenant.common.sms.AliyunSmsUtil;
import com.rc.saas.tenant.common.utils.BeanUtil;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.model.tenant.TenantUserExample;
import com.rc.saas.tenant.search.ugs.UgsMemberSuperLevelOrderSearch;
import com.rc.saas.tenant.search.ugs.UgsMemberSuperLevelSearch;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.sms.TenantSmsService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.service.ugs.UgsMemberSuperLevelOrderService;
import com.rc.saas.tenant.service.ugs.UgsMemberSuperLevelService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.ugs.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author frog
 * @date 2021/4/9
 */
@Controller
@RequestMapping("/ugsMemberSuperLevel")
public class UgsMemberSuperLevelController {

    private static Logger logger = LogManager.getLogger(UgsMemberSuperLevelController.class);

    @Autowired
    private UgsMemberSuperLevelService ugsMemberSuperLevelService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private UidGenerator uidGenerator;

    @Autowired
    private TenantSmsService tenantSmsService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private UgsMemberSuperLevelOrderService ugsMemberSuperLevelOrderService;

    @Autowired
    private TenantUserService tenantUserService;

    /**
     * 跳转超级会员 页面
     */
    @RequestMapping("/index")
    public String ugsMemberSuperLevelPage(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();

        TenantUserExample example = new TenantUserExample();
        example.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andUserTypeEqualTo("0").andStatusEqualTo("0");
        TenantUser adminUser = tenantUserService.selectByExample(example).stream().findFirst().orElseGet(() -> null);

        model.addAttribute("moblie", adminUser.getMobile());
        return "/templates/ugs/ugsMemberSuperLevel";
    }

    /**
     * 查询超级会员数据列表
     *
     * @return
     */
    @RequestMapping("/listPageUgsMemberSuperLevel")
    @ResponseBody
    public WebPageInfo listPageUgsMemberSuperLevel(UgsMemberSuperLevelSearch ugsMemberSuperLevelSearch) {
        PageInfo<UgsMemberSuperLevelResultVo> pageInfo = ugsMemberSuperLevelService.listPageUgsMemberSuperLevel(ugsMemberSuperLevelSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 获取手机短信验证码
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/getSuperLevelAuthCode", method = RequestMethod.POST)
    @ResponseBody
    public TResponse getSuperLevelAuthCode(HttpSession session) {
        TenantUser user = ShiroUtils.getSessionUser();
        TenantUserExample example = new TenantUserExample();
        example.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andUserTypeEqualTo("0").andStatusEqualTo("0");
        TenantUser adminUser = tenantUserService.selectByExample(example).stream().findFirst().orElseGet(() -> null);

        Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());
        //验证码
        String smscode = uidGenerator.genSmsAuthCode();

        SendSmsResponse sendResult = AliyunSmsUtil.sendSms(adminUser.getMobile(), smscode, AliyunSmsTemplateEnum.SUPER_CARD_GIVE, tenant.getSmsSign());

        if (sendResult == null) {
            logger.error("短信系统异常");
            return TResponse.FAIL("短信系统异常");
        }

        if ("OK".equals(sendResult.getCode())) {
            // 更新sms表
            tenantSmsService.updateTenantSmsByTenantCode(tenant.getTenantCode(), adminUser.getMobile(), "0", "tenant,getTicketAuthCode:获取验证码 ,进行赠送超级会员功能:" + adminUser.getMobile(), "获取验证码 ,进行赠送超级会员功能");
        }else {
            logger.error("短信系统异常:" + sendResult.getMessage());
        }

        //将登录验证码保存到会话中
        String sessionAttr = ShiroConstants.SESSION_SENDSUPERMEMBER_UGS_KEY + adminUser.getMobile();
        String sessionAuthCode = smscode + System.currentTimeMillis();
        session.setAttribute(sessionAttr, sessionAuthCode);

        logger.error("获取手机短信验证码 mobile:{},sessionAttr:{},sessionAuthCode:{}", adminUser.getMobile(), sessionAttr, sessionAuthCode);

        return TResponse.SUCCESS("验证码已发送");
    }


    /**
     * 赠送会员等级
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/saveGiveSuperLevel", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveGiveSuperLevel(GiveSuperLevelVo giveSuperLevelVo, HttpSession session) {
        try {
            if (!BeanUtil.isValid(giveSuperLevelVo.getDays(), giveSuperLevelVo.getLevelType(),
                    giveSuperLevelVo.getPhone(), giveSuperLevelVo.getVerificationCode())) {
                return TResponse.FAIL("请输入正确的参数");
            }

            TenantUser user = ShiroUtils.getSessionUser();
            TenantUserExample example = new TenantUserExample();
            example.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andUserTypeEqualTo("0").andStatusEqualTo("0");
            TenantUser adminUser = tenantUserService.selectByExample(example).stream().findFirst().orElseGet(() -> null);

            String sessionAttr = ShiroConstants.SESSION_SENDSUPERMEMBER_UGS_KEY + adminUser.getMobile();
            String sessionAuthCode = (String) session.getAttribute(sessionAttr);

            if (StringUtils.isBlank(sessionAuthCode)) {
                return TResponse.FAIL("未申请验证码");
            }

            if (!giveSuperLevelVo.getVerificationCode().equals(sessionAuthCode.substring(0, 6))) {
                return TResponse.FAIL("验证码错误");
            }


            String[] phones = giveSuperLevelVo.getPhone().split(",");


            //去重
            HashSet<String> set = new HashSet<>();
            for (String phone : phones) {
                set.add(phone);
            }

            List<String> list = new ArrayList<>();
            for (String phone : set) {
                list.add(phone);
            }

            StringBuilder erroMoblies = new StringBuilder();

            List<Long> memberIdList = new ArrayList<>();
            for (String phone : list) {
                MemberInfo memberInfo = memberInfoService.selectMemberByMobile(user.getTenantCode(), phone);
                if (memberInfo == null) {
                    erroMoblies.append(phone).append(",");
                }else {
                    memberIdList.add(memberInfo.getMemberId());
                }
            }
            if (StringUtil.isNotBlank(erroMoblies.toString())){
                return TResponse.FAIL(String.format("手机号%s不是会员,请重新赠送", erroMoblies));
            }
            TResponse tResponse = ugsMemberSuperLevelService.saveGiveSuperLevel(memberIdList, giveSuperLevelVo.getDays(), giveSuperLevelVo.getLevelType(), user.getTenantCode());
            return tResponse;
        } catch (Exception e) {
            logger.error("赠送超级会员失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 批量强制失效
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/batchForcedFailure")
    @ResponseBody
    public Object batchForcedFailure(String memberIdList) {
        try {
            List memberIds = (List) JSONArray.parseArray(memberIdList);
            ugsMemberSuperLevelService.updateBatchForcedFailure(memberIds);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("强制失效失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 跳转会员购买记录页面
     *
     * @return
     */
    @RequestMapping(value = "/buyRecord/{memberId}", method = RequestMethod.GET)
    public String buyRecord(@PathVariable("memberId") Long memberId, Model model) {
        model.addAttribute("memberId", memberId);
        return "/templates/ugs/buyRecord";
    }


    /**
     * 返回会员购买记录记录列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageBuyRecord", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageBuyRecord(UgsMemberSuperLevelOrderSearch ugsMemberSuperLevelOrderSearch) {
        PageInfo<UgsMemberSuperLevelOrderResultVo> pageInfo = ugsMemberSuperLevelOrderService.listPageBuyRecord(ugsMemberSuperLevelOrderSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

}
